package com.atguigu.gulimall.product.bn.controller;

import com.atguigu.gulimall.product.bn.bean.DataToken;
import com.atguigu.gulimall.product.bn.myuntil.UrlMap;
import com.google.gson.Gson;
import org.springframework.http.RequestEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.UriUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author wjj
 * @create 2023-05-01 19:18
 */
@Controller
//@RestController//@RestController注解是springMVC提供的一个复合注解，标识在控制器的类上，就相当于为类添加了@Controller注解，并且为其中的每个方法添加了@ResponseBody注解
public class HttpController {

    private boolean fid = false;//判断是否是消息菜单
    private String encrypt;
    private String jieMiBody;
    private String post2;
    private String s1;//截取字符串中的解密内容，匹配规则
    private String s2;//截取字符串中的消息id，匹配规则
    private String s3;//截取字符串中的消息类型，匹配规则
    private String s4;//截取字符串中的消息文件的fid，匹配规则
    private String type_text;//消息内容
    private String mid;//消息id
    private boolean message_id;//消息id是否存在
    private boolean message_fid;//文件id是否存在
    private String event_type;//消息内心
    private String userJsonStr;//返回格式内容
    private String sfid;//fid值
    private String bodyString;//请求body
    private String sender_account;//请求body

    @RequestMapping("/testRequestBody")
    public String testRequestBody(@RequestBody String requestBody) {
        MyColor.println("requestBody:" + requestBody);
        return "success";
    }

    @RequestMapping("/testRequestEntity")
    public String testRequestEntity(RequestEntity<String> requestEntity) {
        //当前requestEnity表示整个请求报文的信息
        MyColor.println("请求头：" + requestEntity.getHeaders());
        MyColor.println("请求体：" + requestEntity.getBody());
        MyColor.println("");
        return "success";
    }

    @RequestMapping("/testResponse")
    public void testResponse(HttpServletResponse response) throws IOException {
        response.getWriter().print("hello,response");
    }

    @RequestMapping(value = "/testResponseBody", produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String testResponseBody() {
        return "成功";
    }

//    @RequestMapping("/testResponseUser")
//    @ResponseBody
//    public User testResponseUser() {
//        User user = new User(1001, "admin", "123456", 23, "男");
//        return user;
//    }

    @RequestMapping("/testAxios")
    @ResponseBody
    public String testAxios(String username, String password, HttpServletRequest request, HttpServletResponse response) throws IOException {
        MyColor.println(username + "," + password);
//        String localAddr = request.getLocalAddr();
//        int serverPort = request.getServerPort();
//        MyColor.println(localAddr);
//        MyColor.println(serverPort);
//        StringBuffer requestURL = request.getRequestURL();
//        MyColor.println(requestURL);
//        MyColor.println(request.getRequestURI());
//        String substring = requestURL.substring(0, request.getRequestURI().length());
//        MyColor.println(substring);
        String tokenurl = request.getParameter("tokenurl");
        String corpid = request.getParameter("corpid");
        String appid = request.getParameter("appid");
        String posturl = request.getParameter("posturl");
        MyColor.println(tokenurl);
        MyColor.println(corpid);
        MyColor.println(appid);
        MyColor.println(posturl);
        request.setCharacterEncoding("utf-8");
        StringBuffer stringBuffer = new StringBuffer("");
        BufferedReader bufferedReader = request.getReader();
        String str = null;
        while ((str = bufferedReader.readLine()) != null) {
            stringBuffer.append(str);
        }
        str = stringBuffer.toString();
        MyColor.println(str);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        String userJsonStr = "{\"uname\":\"wjj\",\"pwd\":\"ok\"}";

        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        return userJsonStr;
    }

    @RequestMapping("/springMVC-demo4/testBs")
    @ResponseBody
    public String testBs(String tokenurl, String coid, String aid, String toAccount, String jqid,
                         String ast,
                         String posturl, String account, String gid, String timeout,
                         HttpServletRequest request, HttpServletResponse response, HttpSession session) throws Exception {

//        String queryString = request.getQueryString();
//        StringBuffer RequestURL = request.getRequestURL();
//        MyColor.println(RequestURL + "?" + queryString);
//        MyColor.println(username+","+password);
//        String tokenurl = request.getParameter("tokenurl");
//        String corpid = request.getParameter("corpid");
//        String appid = request.getParameter("appid");
//        String posturl = request.getParameter("posturl");
//        String account = request.getParameter("account");
//        String gid = request.getParameter("gid");
//        MyColor.println(request.getRequestURL());
        request.setCharacterEncoding("utf-8");

        Enumeration e = request.getParameterNames();//获取所有参数名
        while (e.hasMoreElements()) {//通过Enumeration类中的hasMoreElements()判断是否还有参数名
            String parameterName = (String) e.nextElement(); //获取当前参数名
            //再通过request.getParameter("")的方法来获取对应参数名的值
            MyColor.println(parameterName + ": " + request.getParameter(parameterName));
        }


        StringBuffer stringBuffer = new StringBuffer("");
        BufferedReader bufferedReader = request.getReader();
        String str = null;
        while ((str = bufferedReader.readLine()) != null) {
            stringBuffer.append(str);
        }
        str = stringBuffer.toString();
        MyColor.println("body内容" + str);
        Gson gson = new Gson();
        DataToken token1 = gson.fromJson(str, DataToken.class);
        String msgSignature = token1.getMsgSignature();
        encrypt = token1.getEncrypt();
        String timeStamp = token1.getTimeStamp();
        String nonce = token1.getNonce();


        jieMiBody = this.encrypt;
        MyColor.println("解密的请求body=" + jieMiBody);
        GetPost getPost1 = new GetPost();
        post2 = getPost1.post2(jieMiBody,  ast);
        MyColor.println("解密后内容=" + post2);
        s2 = "message_id\":\"";
        s3 = "event_type\":\"";
        message_id = post2.contains("message_id");
        message_fid = post2.contains("message_fid");


        event_type = "";
        if (post2 != null && post2 != "") {

            event_type = post2.substring(post2.indexOf(s3) + s3.length(), post2.indexOf("\",\"timestamp"));
        }

        if (post2 != null && post2 != "" && message_id) {
            Gson gson1 = new Gson();
            DataToken token2 = gson1.fromJson(post2, DataToken.class);
            mid = (String) token2.getEvent().get("message_id");
//            mid = post2.substring(post2.indexOf(s2) + s2.length(), post2.indexOf("\",\"message_text"));

        } else {
            mid = "";
        }

        switch (event_type) {
            case "main_tab_add_menu_click":
                type_text = "主界面“+”号菜单项";
                break;

            case "message_menu_click":
                fid = true;
                type_text = "消息菜单";
                break;
            case "chat_toolbar_click":
                type_text = "聊天工具栏";
                break;
            case "slash_command_click":
                type_text = "快捷指令";
                break;
            case "chat_attachment_bar_click":
                type_text = "聊天附件栏";
                break;
            case "mine_menu_click":
                type_text = "“我的”菜单";
                break;
            default:
                type_text = "没有操作类型";
                break;

        }
        MyColor.println("消息id=" + mid);
        if (timeout != null) {
            Thread.sleep(Integer.parseInt(timeout));
        }
        //判断客户输入参数
        String canShu = test.unicodeDecode(post2);
        MyColor.println("正确内容=" + canShu);
        //处理返回参数
        userJsonStr = "";
        //判断是机器还是应用
        if (jqid != null) {
            sender_account = "";

        } else {
            sender_account = "\"sender_account\":\"" + account + "\",\n";
            jqid = account;
        }

        if (canShu.contains("织语") && mid != "") {
            if (canShu.contains("交互")) {
                userJsonStr = "{\n" +
                        //如果以人的身份发送，该人只能是自定义交互的发起人
                        "\"sender_account\":\"" + jqid + "\",\n" +
                        "\"type\":\"text\",\n" +
                        "\"message\": {\n" +
                        "\"refer_msg_id\":\"" + mid + "\",\n" +
                        "\"content\": \"织语帮忙处理交互式引用功能\"\n" +
                        "}\n" +
                        "}";
            } else {

                userJsonStr = "{\n" +
                        //如果以人的身份发送，该人只能是自定义交互的发起人
                        "\"sender_account\":\"" + jqid + "\",\n" +
                        "\"type\":\"text\",\n" +
                        "\"message\": {\n" +
                        "\"refer_msg_id\":\"" + mid + "\",\n" +
                        "\"content\": \"织语帮忙处理文本引用功能\"\n" +
                        "}\n" +
                        "}";
            }
            return userJsonStr;
        } else {
            // 先返回结果，然后异步执行
            ExecutorService executor = Executors.newCachedThreadPool();
            executor.execute(() -> {
                try {
                    Thread.sleep(1000 * 3);
                } catch (InterruptedException e3) {
                    e3.printStackTrace();
                }
//            以下是方法
                GetPost getPost = new GetPost();
                String token = null;
                try {
                    token = getPost.get(tokenurl, coid, aid);
                } catch (Exception exception) {
                    exception.printStackTrace();
                }
                bodyString = "";
                if (gid != null) {
                    if (mid != "") {
                        if (fid) {

                            if (message_fid) {
                                bodyString = "{\n" +
                                        "\"to_group_id\":\"" + gid + "\",\n" +
                                        sender_account +
                                        "\"type\": \"text\",\n" +
                                        "\"message\": {\n" +
                                        "\"content\": \"" + type_text + "(文件)问题已收到，我们将尽快进行排查\"\n" +

                                        "}\n" +
                                        "}";
                            } else {

                                bodyString = "{\n" +
                                        "\"to_group_id\":\"" + gid + "\",\n" +
                                        sender_account +
                                        "\"type\": \"quote\",\n" +
                                        "\"message\": {\n" +
                                        "\"content\": \"" + type_text + "（文字）问题已收到，我们将尽快进行排查\",\n" +
                                        "\"refer_msg_id\":\"" + mid + "\"" +
                                        "}\n" +
                                        "}";
                            }

                        } else {
                            bodyString = "{\n" +
                                    "\"to_group_id\":\"" + gid + "\",\n" +
                                    sender_account +
                                    "\"type\": \"quote\",\n" +
                                    "\"message\": {\n" +
                                    "\"content\": \"" + type_text + "问题已收到，我们将尽快进行排查\",\n" +
                                    "\"refer_msg_id\":\"" + mid + "\"" +
                                    "}\n" +
                                    "}";
                        }


                    } else {
                        bodyString = "{\n" +
                                "\"to_group_id\":\"" + gid + "\",\n" +
                                sender_account +
                                "\"type\": \"text\",\n" +
                                "\"message\": {\n" +
                                "\"content\": \"" + type_text + "使用成功，我们将砥砺前行\"\n" +
                                "}\n" +
                                "}";

                    }


                }
                if (toAccount != null) {
                    bodyString = "{\n" +
                            "\"to_single_account\":\"" + toAccount + "\",\n" +
                            sender_account +
                            "\"type\": \"text\",\n" +
                            "\"message\": {\n" +
                            "\"content\": \"" + type_text + "问题已收到，我们将尽快进行排查\"\n" +
                            "}\n" +
                            "}";
                }
                createSignDemo createSignDemo = new createSignDemo();
                String qianMing = createSignDemo.getQianMing(bodyString, token, ast);
                // 这边执行具体的方法
                try {
                    getPost.post(bodyString, posturl, token,qianMing);
                } catch (Exception exception) {
                    exception.printStackTrace();
                }

            });
            executor.shutdown();

//        StringBuffer stringBuffer = new StringBuffer("");
//        BufferedReader bufferedReader = request.getReader();
//        String str = null ;
//        while((str=bufferedReader.readLine())!=null){
//            stringBuffer.append(str);
//        }
//        str = stringBuffer.toString() ;
//        MyColor.println(str);
//        response.setCharacterEncoding("UTF-8");
//        response.setContentType("application/json;charset=utf-8");

            userJsonStr = "{\n" +
                    "\"result_code\":\"ok\",\n" +
                    "\"result_msg\":\"" + type_text + "，执行成功。\",\n" +
                    "\"result_type\":\"0\"" +
                    "}";


//        response.setCharacterEncoding("utf-8");
//        response.setContentType("text/html;charset=utf-8");


            return userJsonStr;


        }

    }

    @GetMapping("/springMVC-demo4/testBs1")
    public String testBs1(String encrypt, String msgSignature, String timeStamp, String nonce,
                          HttpServletRequest request, HttpSession session, String ast) throws Exception {
        request.setCharacterEncoding("utf-8");
        System.out.println("+++++=" + request.getParameter("encrypt"));
        String queryString = request.getQueryString();//所有请求参数的字符串
        StringBuffer requestURL = request.getRequestURL();//请求地址（包含工程名）
//        MyColor.println(request.getRequestURI());//请求工程名
        Enumeration e = request.getParameterNames();//获取所有参数名
        while (e.hasMoreElements()) {//通过Enumeration类中的hasMoreElements()判断是否还有参数名
            String parameterName = (String) e.nextElement(); //获取当前参数名
            //再通过request.getParameter("")的方法来获取对应参数名的值
            MyColor.println(parameterName + ": " + request.getParameter(parameterName));
        }
        UrlMap urlMap = new UrlMap();
        Map<String, String> strUrlMap = urlMap.urlMap(queryString);
        encrypt = strUrlMap.get("encrypt");
//        String sss = "&encrypt=";
//        if (queryString != null) {
//
//            encrypt = queryString.substring(queryString.indexOf(sss) + sss.length());
//            MyColor.println("未解密前" + encrypt);
//        }
        MyColor.println("未解密前" + encrypt);
        if (encrypt != null) {

            encrypt = UriUtils.decode(encrypt, "utf-8");
        }

        String jieMiBody = encrypt;
        MyColor.println("解密的请求body=" + jieMiBody);
        GetPost getPost1 = new GetPost();
        post2 = getPost1.post2(jieMiBody,  ast);
        MyColor.println("解密后内容=" + post2);
        session.setAttribute("mimi", post2);
        session.setAttribute("bsUrl", requestURL + "?" + queryString);
        return "success";
    }
//
//
//    @RequestMapping("/testBs2")
//    @ResponseBody
//    public String testBs2(String account, String toAccount,
//                          HttpServletRequest request, HttpServletResponse response) throws Exception {
//        String queryString = request.getQueryString();
//        StringBuffer RequestURL = request.getRequestURL();
//        MyColor.println(RequestURL + "?" + queryString);
//        String bodyString = "{\n" +
//                "\"to_single_account\":\"" + toAccount + "\",\n" +
//                "\"sender_account\": \"" + account + "\",\n" +
//                "\"type\": \"text\",\n" +
//                "\"message\": {\n" +
//                "\"content\": \"问题已收到，我们将将延迟处理\"\n" +
//                "}\n" +
//                "}";
//        Thread.sleep(10000);
//        GetPost getPost = new GetPost();
//        String token = getPost.get("https://iccwork.360.cn:8888/v2/gettoken",
//                "2638896626146546", "2638896626166440");
//        getPost.post(bodyString, "https://iccwork.360.cn:8888/v2/message/send_to_conversation", token);
//        request.setCharacterEncoding("utf-8");
//        response.setCharacterEncoding("UTF-8");
//        response.setContentType("application/json;charset=utf-8");
////        String userJsonStr="{\"sender_account\":\""+account+"\",\"结果\":\"ok\"}";
//        String userJsonStr = "{\n" +
//                "\"result_code\":\"ok\",\n" +
//                "\"result_msg\":\"处理中\",\n" +
//                "\"result_type\":\"0\""+
////                "\"message\": {\n" +
////                "\"content\": \"<at username=shizhanying>，问题已收到，我们将延迟处理\"\n" +
////                "}\n" +
//                "}"
//                ;
//
//        response.setCharacterEncoding("utf-8");
//        response.setContentType("text/html;charset=utf-8");
//
//        return userJsonStr;
//    }


}
